<template>
  <el-card class="form-container" shadow="never">
    <el-tree
      :data="menuTreeList"
      show-checkbox
      node-key="id"
      ref="tree"
      highlight-current
      :props="defaultProps"
    ></el-tree>
    <div style="margin-top: 20px" align="center">
      <el-button type="primary" @click="handleSave()">保存</el-button>
      <el-button @click="handleClear()">清空</el-button>
    </div>
  </el-card>
</template>

<script>
import { fetchTreeList } from "@/api/menu";
import { listMenuByRole, allocMenu } from "@/api/role";

export default {
  name: "allocMenu",
  data() {
    return {
      menuTreeList: [],
      defaultProps: {
        children: "children",
        label: "title"
      },
      roleId: null
    };
  },
  created() {},
  methods: {
    initdata() {
      this.roleId = this.$root.permission.allocMenu.id;
      this.treeList();
      this.getRoleMenu(this.roleId);
    },
    treeList() {
      fetchTreeList().then(response => {
        this.menuTreeList = response.data;
      });
    },
    getRoleMenu(roleId) {
      listMenuByRole(roleId).then(response => {
        let menuList = response.data;
        let checkedMenuIds = [];
        let residsobj = {}
        menuList.map(item => {
          residsobj[item.id] = ''
        })
        if (menuList != null && menuList.length > 0) {
          for (let i = 0; i < menuList.length; i++) {
            let menu = menuList[i];
            residsobj[menu.id] = ''
            if (menu.parentId !== 0) {
              // checkedMenuIds.push(menu.id);
              delete residsobj[menu.parentId]

            }
          }
        }
        this.$refs.tree.setCheckedKeys(Object.keys(residsobj));
      });
    },
    handleSave() {
      let checkedNodes = this.$refs.tree.getCheckedNodes();
      let checkedMenuIds = new Set();
      if (checkedNodes != null && checkedNodes.length > 0) {
        for (let i = 0; i < checkedNodes.length; i++) {
          let checkedNode = checkedNodes[i];
          checkedMenuIds.add(checkedNode.id);
          if (checkedNode.parentId !== 0) {
            checkedMenuIds.add(checkedNode.parentId);
          }
        }
      }

      let params = new URLSearchParams();
      params.append("roleId", this.roleId);
      params.append("menuIds", Array.from(checkedMenuIds));
      allocMenu(params).then(response => {
        this.$message({
          message: "分配成功",
          type: "success",
          duration: 1000
        });
        this.$parent.$parent.isshowmenudia = false;
      });
    },
    handleClear() {
      this.$refs.tree.setCheckedKeys([]);
    }
  }
};
</script>

<style scoped>
</style>
